<%--
  Created by IntelliJ IDEA.
  User: 29688
  Date: 2021/4/1
  Time: 16:38
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>发布公告</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/layui-v2.5.7/layui/css/layui.css"
          media="all">
    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/layui-v2.5.7/style/admin.css"
          media="all">
    <script src="${pageContext.request.contextPath}/layui-v2.5.7/layui/layui.js"></script>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <script src="${pageContext.request.contextPath}/js/jquery.js" type="text/javascript"></script>
</head>
<body>

<div class="layui-fluid">
    <table class="layui-hide" id="test" lay-filter="test">
    </table>
    <script type="text/html" id="toolbarDemo">
        <div>
            <button type="button" class="layui-btn layui-btn-sm" lay-event="add">
                <i class="layui-icon">&#xe608;</i>发布公告
            </button>
            <button type="button" class="layui-btn layui-btn-sm" lay-event="delSelect">
                <i class="layui-icon">&#xe640;</i> 删除
            </button>
            <button class="layui-btn layui-btn-sm" lay-event="getCheckData">获取选中行数据</button>
        </div>
    </script>
    <script type="text/html" id="barDemo">
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    </script>
</div>

</body>
<div class="layui-fluid" id="addMessage" hidden>
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-header">发布公告</div>
                <div class="layui-card-body" pad15>
                    <form class="layui-form"> <!-- 提示：如果你不想用form，你可以换成div等任何一个普通元素 -->
                        <div class="layui-form-item">
                            <label class="layui-form-label">发送对象</label>
                            <div class="layui-input-block" id="roleList">
                                <input type="checkbox" name="sendRole" title="普通用户" value="1" checked>
                                <input type="checkbox" name="sendRole" title="管理员" value="2" checked>
                            </div>
                        </div>

                        <div class="layui-form-item layui-form-text">
                            <label class="layui-form-label">公告内容</label>
                            <div class="layui-input-block">
                                <textarea name="remarks" placeholder="请输入公告内容" class="layui-textarea"></textarea>
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <div class="layui-input-block">
                                <input type="button" class="layui-btn" lay-filter="formDemo" lay-submit value="发布">
                            </div>
                        </div>

                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
    var close;
    layui.use(['table', 'layer', 'form', 'util'], function () {
        var table = layui.table;
        var form = layui.form;
        var layer = layui.layer;
        var util = layui.util;
        /*表格渲染*/
        table.render({
            elem: '#test'
            , url: '/user/message/selectAll?rid=3'
            , toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
            , title: '用户数据表'

            , cols: [[
                /*设置序号*/
                {type: 'numbers', fixed: 'left', title: "id"},
                {type: 'checkbox', fixed: 'left'}
                , {field: 'mid', title: 'ID', width: 80, fixed: 'left', hide: true}
                , {field: 'mname', title: '公告内容', width: 300, edit: 'text'}
                , {
                    field: 'rname', title: '接收者', width: 150, text: '未绑定', edit: 'text', sort: true
                }, {
                    field: 'createdate', title: '创建时间', width: 300, templet: function (d) {
                        return util.toDateString(d.createdate, "yyyy-MM-dd HH:mm:ss")
                    }
                }
                , {fixed: 'right', title: '操作', toolbar: '#barDemo', width: 150}
            ]]
            , page: true,
            skin: 'row',
            even: 'true',
            id: 'bookTable'
        });

        /*发布公告*/
        form.on('submit(formDemo)', function (data) {
            console.log("发布事件触发！")
            var role = 0
            /*获取所复选框*/
            $('#roleList input[type=checkbox]:checked').each(function () {
                role += parseInt($(this).val())
            })
            var postData = {'rid': role, 'mname': data.field.remarks}
            console.log(role)
            console.log(data.field)
            if (role === 0) {
                layer.msg("至少有一个角色接收！");
                return false;
            } else {
                $.ajax({
                    url: '/admin/message',
                    type: "post",
                    data: postData,
                    dataType: 'json',
                    traditional: true,
                    /*防止深度序列化*/
                    success: function (data) {
                        if (data === 1) {
                            layer.msg("发布成功！")
                        } else {
                            layer.msg("未知异常!")
                        }

                    }
                })
            }

            layer.close(close)
            console.log("数据表格重新渲染")
            table.reload('bookTable');
        })


        /*头部事件栏*/
        table.on('toolbar(test)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id);
            switch (obj.event) {
                case 'getCheckData':
                    var data = checkStatus.data;
                    layer.alert(JSON.stringify(data));
                    break;
                case 'delSelect':
                    layer.confirm('真的删除所有选中行？', {icon: 3, title: '询问'}, function () {
                        var data = checkStatus.data;
                        if (data.length > 0) {
                            /*后端删除*/
                            var ids = []
                            for (let i = 0; i < data.length; i++) {
                                ids.push(parseInt(data[i].mid))
                            }
                            console.log(ids);


                            /*前端删除*/
                            layer.confirm('确定删除选中' + data.length + '条数据？', {
                                icon: 3,
                                title: '提示信息'
                            }, function (index) {
                                //layui中找到CheckBox所在的行，并遍历找到行的顺序
                                $("div.layui-table-body table tbody input[name='layTableCheckbox']:checked").each(function () { // 遍历选中的checkbox
                                    n = $(this).parents("tbody tr").index();  // 获取checkbox所在行的顺序
                                    //移除行
                                    $("div.layui-table-body table tbody ").find("tr:eq(" + n + ")").remove();
                                    //如果是全选移除，就将全选CheckBox还原为未选中状态
                                    $("div.layui-table-header table thead div.layui-unselect.layui-form-checkbox").removeClass("layui-form-checked");

                                });
                                /*后端删除*/
                                if(deleteByIds(ids)>0){
                                    layer.msg("删除成功！")
                                }
                                layer.close(index);
                            })
                        } else {
                            layer.msg("请选择需要删除的行");
                        }
                    });
                    break;
                case 'add':
                    close = layer.open({
                        type: 1
                        , content: $('#addMessage'),
                    });

            }

        });

        /*删除书籍的方法*/
        function deleteMessage(mid) {
            $.ajax({
                url: "/admin/message/delete?mid=" + mid, function(data) {
                    console.log(data)
                }
            })
        }

        /*批量删除用户的方法*/
        function deleteByIds(ids) {
            $.ajax({
                type: "post",
                data: {"ids": ids},
                url: "/user/message/deleteByIds",
                dataType: 'json',
                traditional: true
            })
        }
        //监听行工具事件
        table.on('tool(test)', function (obj) {
            var data = obj.data;
            if (obj.event === 'del') {
                layer.confirm('真的删除行么', function (index) {
                    obj.del();
                    layer.close(index);
                    deleteMessage(obj.data.mid)
                });
            }
        });
    });

</script>
</html>

